package com.nulldev.util.web.nCaptcha.backend;

import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Map;

import com.nulldev.util.image.ImageUtil;
import com.nulldev.util.image2.textobf.TextObf;
import com.nulldev.util.image2.textobf.TextObf.ObfuscationMethod;
import com.nulldev.util.java.DataSet;
import com.nulldev.util.other.ByteUtils;
import com.nulldev.util.uri.URIUtil;
import com.nulldev.util.uri.URIUtil2;
import com.nulldev.util.uri.server.HttpPage;
import com.nulldev.util.uri.server.RequestType;
import com.nulldev.util.web.nCaptcha.nCaptcha;
import com.nulldev.util.web.nCaptcha.backend.user.User;
import com.nulldev.util.web.nCaptcha.backend.user.UserManager;

public class RequestCaptchaNS extends HttpPage {

	public RequestCaptchaNS() {
		super("/generate_captcha_fallback");
		this.replyOverBytes(true);
	}
	
	private final BufferedImage adone = TextObf.obfuscate("Captcha already finished.", ObfuscationMethod.None);
	private final String adone_b64 = ImageUtil.convertImageDataBase64(this.adone);
	
	private final BufferedImage failed = TextObf.obfuscate("You seem to be a bot, try again later.", ObfuscationMethod.None);
	private final String failed_b64 = ImageUtil.convertImageDataBase64(this.failed);
	
	@Override
	public String handleRequest(String args, String ip, RequestType type) {
		return "UNSUPPORTED";
	}

	/**
	 * Unused
	 */
	@Override
	public byte[] handleRequest_Alt(String args, String ip, RequestType type) {
		final Map<String, List<String>> requests = URIUtil2.splitQuery(URIUtil.safeCreate(args));
		final User user = UserManager.registerOrLoadUser(ip);
		if (user.captchaDone()) {
			return ByteUtils.fromBase64(this.adone_b64);
		}
		if (user.isNotBot()) {
			final Captcha c = nCaptcha.randomCaptcha();
			final DataSet<String, String[]> b64 = c.generateBase64Image(user.getLevel());
			user.setExpectedResults(b64.getB());
			return ByteUtils.fromBase64(b64.getA());
		}else {
			return ByteUtils.fromBase64(this.failed_b64);
		}
	}

}
